import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';
import { NotificationService, BullySubjectService } from 'app/shared/service';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter } from 'rxjs/operators';
import { SYSTEM_EVENT, MESSAGE_CHANNEL, SELECT_OPTIONS } from 'app/app.constants';
import { EquipmentService } from '../equipment.service';
import { ToolbarComponent } from 'app/public/toolbar/toolbar.component';
import { PublicService } from 'app/public/public.service';
import * as moment from 'moment';
import { MessagesService } from 'app/shared/service';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';
import { SystemService } from 'app/service/system.service';
import { AuthService } from 'app/auth/auth.service';

@Component({
    selector: 'itmp-equipment-list',
    templateUrl: './equipment-list.component.html',
    styleUrls: ['./equipment-list.component.css']
})
export class EquipmentListComponent implements OnInit, OnDestroy {
    @ViewChild(ToolbarComponent) private _toolbarCom: ToolbarComponent = null;
    search$ = new Subject<object>();
    pagination: any; // 分页数据的对象
    searchData: any; // 搜索数据的对象
    listOfData = null; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    toolbarList = [
        // 工具条栏
        // { className: 'icon-chakan' },
        { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' },
        // { className: 'icon-screenfull' },
        { className: 'icon-xiazai' }
    ];
    // 筛选框下拉列表
    selectionList = {
        Type: [],
        Direction: ['West', 'East', 'South', 'North'],
        // Status: ['OK', 'Faulty', 'Warning', 'Off-line']
        Status: ['OK', 'FAULTY', 'OFFLINE']
    };
    selectEquipment = null; // 选择的设备信息（对象）
    selectEquipmentData = null; // 选择的设备信息（对象）
    selectType = null;
    addEquipmentTitle: string;
    isVisible = false;
    isPhotoVisible = false;
    isCctvVideoVisible = false;
    isVMSModalVisible = false;
    isVMSErrVisible = false;
    url = [];
    zoneIdList = [];
    // 设备分类计数信息
    showEquipmentNum = {
        show: false,
        total: 0,
        faulity: 0,
        type: 'VMS'
    };
    subscription: Subscription = null;
    isTaskFromGis = false;
    updatedDate = null;

    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false,
        export: false,
        GIS: false,
        Setting: false,
        Look: false,
        Warning: false
    };
    isForce = false;
    isForceVisible = false;
    userZoneIdList = [];
    selectVmsErr = {};

    constructor(
        private modalService: NzModalService,
        private msg: NotificationService,
        private bully: BullySubjectService,
        public eqt: EquipmentService,
        public pub: PublicService,
        private msgErr: MessagesService,
        private translate: TranslateService,
        private ss: SystemService,
        private authService: AuthService
    ) {}

    ngOnInit() {
        this.getZoneIdListByUser();
        this.searchPipeSet();
        const res = this.pub.getSelectOptionsList(SELECT_OPTIONS.EQUIPMENT_TYPE);
        this.selectionList.Type = res.data;
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.selectionList.Type.forEach(site => {
                site.displayName = site.vietName;
            });
        } else {
            this.selectionList.Type.forEach(site => {
                site.displayName = site.name;
            });
        }
        this.changeLang();
        // this.selectionList.Type = this.eqt.typeArr;
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'eqtId',
                isChecked: true
            },
            {
                name: 'zone_ID',
                key: null,
                value: 'zoneId',
                isChecked: true
            },
            {
                name: 'RoadName',
                key: null,
                value: 'roadName',
                isChecked: true
            },
            {
                name: 'Direction',
                key: null,
                value: 'direction',
                isChecked: true
            },
            {
                name: 'Type',
                key: null,
                value: 'eqtType',
                isChecked: true
            },
            {
                name: 'Updated_Date',
                key: null,
                value: 'updatedDate',
                isChecked: true
            },
            {
                name: 'Status',
                key: null,
                value: 'status',
                isChecked: true
            }
        ];
        this.initData();
        this.getData();
        this.bully.zoneListBehavior.subscribe(res1 => {
            this.zoneIdList = res1['selectZoneList'];
            this.getData();
        });
        // 接受地图发来的设备创建消息
        this._createEquipmentEventHandle();
        this.getButtonAccess();
    }

    changeLang() {
        this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (res.data === 'vi') {
                this.selectionList.Type.forEach(site => {
                    site.displayName = site.vietName;
                });
            } else {
                this.selectionList.Type.forEach(site => {
                    site.displayName = site.name;
                });
            }
        });
    }

    ngOnDestroy() {
        this.bully.resetBSubject();
        if (this.subscription) {
            this.bully.resetBSubject();
            this.subscription.unsubscribe();
        }
    }

    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('17', this.accessButton);
    }

    // 获取选择设备的计数信息
    getEquCountData() {
        this.eqt.getAllDeviceStatusStatistics().subscribe(res => {
            let data;
            res.data.forEach(item => {
                if (item.eqtType === +this.searchData.eqtType) {
                    data = item;
                }
            });
            this.showEquipmentNum = {
                ...this.showEquipmentNum,
                show: true,
                total: data.faultySum + data.okSum,
                faulity: data.faultySum
            };
            setTimeout(() => {
                this.showEquipmentNum.show = false;
            }, 5000);
        });
    }

    // 防抖函数注册
    searchPipeSet() {
        this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.selectionList.Type.map(item => {
                const is = item.value === this.searchData.eqtType;
                if (is) {
                    this.showEquipmentNum.type = item.name;
                    let isCount = true;
                    for (const key in this.searchData) {
                        if (this.searchData.hasOwnProperty(key)) {
                            const element = this.searchData[key];
                            if (key !== 'eqtType' && element) {
                                isCount = false;
                                break;
                            }
                        }
                    }
                    if (isCount) {
                        this.getEquCountData();
                    }
                }
            });
            this.getData();
        });
    }

    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }

    // 初始化分页和搜索
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            eqtId: null,
            zoneId: null,
            roadName: null,
            direction: null,
            eqtType: null,
            startTime: null,
            endTime: null,
            status: null,
            connectionStatus: null,
            constructionPerson: null,
            constructionUnit: null,
            deviceName: null,
            ipAddr: null,
            latitude: null,
            longitude: null,
            supervisionEngineers: null
        };
        this.listOfData = [];
        this.updatedDate = null;
    }

    // 获取数据
    getData() {
        // this.listOfData = [];
        this.selectEquipment = null; // 选择的设备信息（对象）
        this.selectEquipmentData = null; // 选择的设备信息（对象）
        this.searchData.updatedDate = null;
        const params = {
            condition: { ...this.searchData, zoneIdList: this.zoneIdList },
            exportType: null,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.eqt.getEquipmentList(params).subscribe(res => {
            const data = res.content;
            if (!data) {
                this.listOfData = [];
                return;
            }
            this.listOfData = data.content;
            this.pagination.totalEle = data.totolElements;
            this.pagination.currentSize = data.numberOfElements;
            this.listOfData.forEach((item, index) => {
                this.listOfData[index].blackList = this.eqt.changeDate(item.blackList, 1);
                this.listOfData[index].installDate = this.eqt.changeDate(item.installDate, 1);
                this.listOfData[index].netDate = this.eqt.changeDate(item.netDate, 1);
            });
        });
    }

    // 新增和编辑功能
    addOrEdit(flag) {
        this.isTaskFromGis = false;
        if (flag === 'add') {
            this.addEquipmentTitle = 'Add_Equipment';
            this.cancelActive();
            this.isVisible = true;
        } else {
            this.addEquipmentTitle = 'Edit_Equipment';
            if (this.selectEquipment && this.selectEquipment.id) {
                if (!this.authService.isUserZoneChecked(this.selectEquipment.zoneID)) {
                    return;
                }
                this.isVisible = true;
            } else {
                this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.select_notify' });
            }
        }
    }

    // 取消强制操作
    FourchHandleCancel() {
        this.isForceVisible = false;
    }

    // 确定强制操作
    ForceHandleOk() {
        this.isForceVisible = false;
        this.isForce = true;
        this.doDelete();
    }

    // 获取用户的ZoneIdList
    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.eqt.getAllUser(queryData).subscribe(res => {
            const userZone = res.content.content[0].userZoneRel;
            userZone.forEach(zoneId => {
                this.userZoneIdList.push(zoneId.vnqn_zone_id);
            });
        });
    }

    // 执行删除操作
    doDelete() {
        const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
        const header = {
            zoneId: zoneIds.join(','),
            isFource: this.isForce
        };
        this.eqt.deleteDevices(this.selectEquipment.id, header).subscribe(res => {
            if (JSON.parse(res)['code'] === '900103') {
                this.isForceVisible = true;
            } else {
                this.isForceVisible = false;
                // 判断当前页是否有数据
                if ((this.pagination.totalEle - 1) / this.pagination.pageSize === this.pagination.currentPage - 1) {
                    this.pagination.currentPage = 1;
                }
                this.getData();
                this.selectEquipment = null;
            }
        });
    }

    // 删除
    delete(): void {
        if (this.selectEquipment && this.selectEquipment.id) {
            if (!this.authService.isUserZoneChecked(this.selectEquipment.zoneID)) {
                return;
            }
            const tempTranslate = [
                { title: 'EquipmentManagement.EquipmentManagement.Delete Equipment' },
                { title: 'EquipmentManagement.EquipmentManagement.Are you sure you want to remove this Equipment' },
                { title: 'EquipmentManagement.EquipmentManagement.OKText' },
                { title: 'EquipmentManagement.EquipmentManagement.NO' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.doDelete();
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        } else {
            this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.select_notify' });
        }
    }

    // 刷新
    refresh(): void {
        this.cancelActive();
        this.initData();
        this.getData();
    }

    // 取消选中
    cancelActive(): void {
        this.selectEquipment = {
            id: null,
            nextDate: null,
            type: null,
            supervision: null,
            ip: null,
            installDate: null,
            zoneID: null,
            constructionUnit: null,
            longitude: null,
            constructionPerson: null,
            latitude: null,
            roadName: null,
            direction: null,
            url: null
        };
        this.selectType = null;
        this.selectEquipmentData = null;
        this.listOfData.forEach((data, index) => {
            data.active = false;
        });
    }

    // 点击tr取值
    clickTR(i): void {
        this.addEquipmentTitle = 'Edit User';
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectEquipment = {
                    id: data.eqtId,
                    nextDate: data.netDate,
                    type: '' + data.eqtType,
                    supervision: data.supervisionEngineers,
                    ip: data.ipAddr,
                    installDate: data.installDate,
                    zoneID: data.zoneId,
                    constructionUnit: data.constructionUnit,
                    longitude: data.longitude,
                    constructionPerson: data.constructionPerson,
                    latitude: data.latitude,
                    roadName: data.roadName,
                    direction: data.direction,
                    url: data.url,
                    status: data.status,
                    connectionStatus: data.connectionStatus
                };
                this.selectType = data.eqtType;
                this.selectEquipmentData = data;
            }
        });
    }

    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }

    // 打开弹框展示图片
    showPhoto(event, index) {
        event.stopPropagation();
        this.url = this.listOfData[index].url;
        this.isPhotoVisible = true;
    }

    // 设置VMS设备
    showVMS() {
        this.isVMSModalVisible = true;
    }

    // 设置vmsErr
    showVMSErr() {
        this.eqt.getVmsErr(this.selectEquipmentData.eqtId).subscribe(res => {
            const tempVmsErr = JSON.parse(res);
            if (Object.keys(tempVmsErr.data).length) {
                this.selectVmsErr = tempVmsErr.data;
                this.isVMSErrVisible = true;
            } else {
                this.msgErr.warning('No data found');
            }
        });
    }

    // 定位
    positioning(selectData) {
        if (!selectData) {
            this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.select_notify' });
            return;
        }
        const data = {
            type: (selectData['eqt_type'] + '').toLowerCase() + '-position',
            data: selectData
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, data);
    }

    private _createEquipmentEventHandle() {
        this.subscription = this.bully
            .getBSubject()
            .pipe(filter(res => !!res))
            .subscribe(res => {
                if (res['type'] === SYSTEM_EVENT.CREATE_EVENT) {
                    const data = res['data'];
                    // 关闭所有弹窗
                    this.isPhotoVisible = false;
                    this.isVMSModalVisible = false;

                    // 取消选中
                    this.cancelActive();

                    // 补填数据
                    this.selectEquipment.longitude = data['longitude'];
                    this.selectEquipment.latitude = data['latitude'];
                    this.selectEquipment.roadName = data['roadName'];
                    this.selectEquipment.zoneID = data['zoneID'];

                    // 新建设备
                    this.isTaskFromGis = true;
                    this.addEquipmentTitle = 'Add_Equipment';
                    this.isVisible = true;
                }
            });
    }

    // 日历框事件
    onDateOk(result: Date): void {
        // this.searchData.startTime = this.eqt.changeDate(result[0], 0);
        // this.searchData.endTime = this.eqt.changeDate(result[1], 0);
        this.searchData.startTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.searchData.endTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.onSearch('startTime');
    }

    // 定位新建的设备
    positionNewDevice(e) {
        if (e && this._toolbarCom) {
            this._toolbarCom.selectData = e;
            this._toolbarCom.positioning();
        }
    }

    cctvClick(event) {
        this.isCctvVideoVisible = true;
        this.selectEquipmentData = event;
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
